package com.up4years.dataapi.service.support;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.springframework.stereotype.Service;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.Bucket;
import com.aliyun.oss.model.CompleteMultipartUploadRequest;
import com.aliyun.oss.model.InitiateMultipartUploadRequest;
import com.aliyun.oss.model.InitiateMultipartUploadResult;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PartETag;
import com.aliyun.oss.model.UploadPartRequest;
import com.aliyun.oss.model.UploadPartResult;
import com.up4years.utils.CommonUtil;
@Service
public class OSSService {
	Logger logger = Logger.getLogger(OSSService.class);
	public void mkdir(String path){
		if(StringUtils.isBlank(path)||!path.startsWith("/")||!path.endsWith("/")){
			throw new IllegalArgumentException("文件夹必须以'/'开头，形如'/a/b/c'");
		}
	}
	
	public boolean simpleUpload(String fileName,InputStream is){
 	    OSSClient client = this.getClient();
 	    logger.debug("创建上传Object的Metadata");
 	    ObjectMetadata meta = new ObjectMetadata();
 	    logger.debug("必须设置ContentLength");
 	    try {
			meta.setContentLength(is.available());
		} catch (IOException e) {
 			e.printStackTrace();
		}
 	    logger.debug("上传Object");
	    client.putObject(this.getBucket().getName(), fileName, is, meta);
	    if(is!=null){
	    	try {
				is.close();
			} catch (IOException e) {
 				e.printStackTrace();
			}
	    }
		return true;
	}
	/**
	 * 暂不启用
	 * @param fileName
	 * @param is
	 * @return
	 */
	@Deprecated
	private boolean multipartUpload(String fileName,InputStream is){
		try{
 		logger.debug("开始Multipart Upload");
		InitiateMultipartUploadRequest initiateMultipartUploadRequest = new InitiateMultipartUploadRequest(this.getBucket().getName(), fileName);
		InitiateMultipartUploadResult initiateMultipartUploadResult = this.getClient().initiateMultipartUpload(initiateMultipartUploadRequest);
		// 打印UploadId
		logger.debug("UploadId:"+initiateMultipartUploadResult.getUploadId());
		logger.debug("设置每块为 5M");
		final int partSize = 1024 * 1024 * 5;
		logger.debug("计算分块数目");
		int partCount = (int) (is.available() / partSize);
		if (is.available() % partSize != 0){
		    partCount++;
		}
		logger.debug("新建一个List保存每个分块上传后的ETag和PartNumber");
		List<PartETag> partETags = new ArrayList<PartETag>();
		for(int i = 0; i < partCount; i++){
		    long skipBytes = partSize * i;
		    logger.debug("跳到每个分块的开头"+skipBytes);
		    is.skip(skipBytes);
		    long size = partSize < is.available() - skipBytes ? partSize : is.available() - skipBytes;
		    logger.debug("计算每个分块的大小"+size);
		    logger.debug("创建UploadPartRequest，上传分块");
 		    UploadPartRequest uploadPartRequest = new UploadPartRequest();
		    uploadPartRequest.setBucketName(this.getBucket().getName());
		    uploadPartRequest.setKey(fileName);
		    uploadPartRequest.setUploadId(initiateMultipartUploadResult.getUploadId());
		    uploadPartRequest.setInputStream(is);
		    uploadPartRequest.setPartSize(size);
		    uploadPartRequest.setPartNumber(i + 1);
		    UploadPartResult uploadPartResult = this.getClient().uploadPart(uploadPartRequest);
		    logger.debug("将返回的PartETag保存到List中。");
 		    partETags.add(uploadPartResult.getPartETag());
 		    logger.debug("关闭文件");
		}
		is.close();
		CompleteMultipartUploadRequest completeMultipartUploadRequest =
		        new CompleteMultipartUploadRequest(this.getBucket().getName(),fileName, initiateMultipartUploadResult.getUploadId(), partETags);
		this.getClient().completeMultipartUpload(completeMultipartUploadRequest);
		logger.debug("完成分块上传");
 		}catch(IOException e){
			e.printStackTrace();
		}
		return true;
	}
	/**
	 * 暂不启用
	 * @param fileName
	 * @param is
	 * @return
	 */
	@Deprecated
	public boolean upload(String fileName,InputStream is){
		if(StringUtils.isBlank(fileName)){
			throw new IllegalArgumentException("未指定文件名！");
		}
		if(is==null){
			throw new IllegalArgumentException("未指定文件内容！");
		}
		try {
			if(is.available()/1024/1024>=10){
				logger.debug("文件大于10M 选择分块上传");
				return multipartUpload(fileName, is);
			}else{
				logger.debug("文件小于10M 选择直接上传");
				return simpleUpload(fileName, is);
			}
		} catch (IOException e) {
 			e.printStackTrace();
		}
		return true;
	}
	private OSSClient getClient(){
		String key = CommonUtil.getALI_AccessKeyID();
		String secret = CommonUtil.getALI_AccessKeySecret();
		String endpoint = "http://" + CommonUtil.getALI_ENDPOINT();
		OSSClient client = new OSSClient(endpoint, key, secret);
		return client;
  	}
	
	public Bucket getBucket(){
 		Bucket bucket = new Bucket(CommonUtil.getALI_BucketName());
 		return bucket;
	}
	@Test
	public void test() throws IOException{
		File f= new File("F:\\video\\想起 电视剧-愤怒的蝴蝶-主题曲-韩雪.mp4");
   		OSSService os = new OSSService();
		System.out.println(os.upload("韩雪.mp4", new FileInputStream(f)));;
 	}
	
}
